<template>
	<view class="index-bg vh-100 text-white ">
		<y-nav>
			<view class="flex w-p-100 gap-12 flex-y-center px-16 flex-x-space-between"
				@click="$page.open('/pages/user/index')">
				<image :src="USERINFO?.avatar?USERINFO?.avatar:WEBCONFIG?.web_logo" class="avatar round-circle"></image>
				<view class="fs-17 flex-1 text-ellipsis-1">{{USERINFO?.nickname?USERINFO?.nickname:WEBCONFIG?.web_name}}
				</view>
				<view class="flex flex-y-center" @click.stop="adPopup.open();">
					<view class="w-26 h-26 round-6 gradient flex flex-center fs-14">
						免
					</view>
					<view class="relative left--1 flex flex-center h-22 round-right-30 px-7 fs-12"
						style="background-color: rgba(0, 0, 0, 0.5);">
						{{USERINFO?.productions}}次
					</view>
				</view>
			</view>
		</y-nav>
		<view class="py-20 px-8 " :style="`padding-bottom: ${70 + safeBottom}px !important;`">
			<view class="flex flex-center" v-if="WEBCONFIG?.is_show_ad_video==1">
				<view class="w-230">
					<ySetup v-model="form.type" @onChange="initVideoTypeList"></ySetup>
				</view>
			</view>
			<view class="mt-20 round-12 bg-black-1 py-18 px-12 flex flex-y-center gap-2" v-if="form.type==2">
				<text class="fw-600 ">产品名称：</text>
				<input placeholder="请输入您的产品名称..." v-model="form.product_name" />
			</view>
			<view class="mt-20">
				<yTitle>
					<template #icon>
						<text class="iconfont icon-miaoshu fw-400"></text>
					</template>
					描述你的视频
				</yTitle>

				<!-- #ifdef MP-WEIXIN -->
				<view class="mt-20 " v-if="WEBCONFIG?.wx_ad_status.includes('wx_video')">
					<ad :unit-id="WEBCONFIG?.wx_video" ad-theme="white">
					</ad>
				</view>
				<!-- #endif -->

				<view class="mt-12 bg-black-1 round-12  p-8 pb-16 fs-14">
					<view class="bg-black-2 px-10 py-12 round-12 ">
						<textarea class="w-p-100 h-120" :maxlength="WEBCONFIG?.max_prompt" v-model="form.prompt"
							placeholder="详细描述你想创建的视频场景...例如：未来科技城市，飞行器在高楼间穿梭，全息投影广告闪烁，机器人在街道上行走，充满科幻感的场景..."></textarea>
						<view class="flex flex-x-flex-end mt-6">
							<text class="text-999 ">{{form.prompt.length}} /{{WEBCONFIG?.max_prompt}}</text>
						</view>
					</view>
					<view class="flex flex-y-center flex-x-space-between mt-16">
						<view class="flex text-grey fs-14 gap-4" @click="form.prompt=''">
							<text class="iconfont icon-clear-area"></text>
							清空内容
						</view>
						<view class="flex flex-y-center gap-6">
							<view class="ai py-10 px-12 flex flex-center gap-4 round-6" @click="openAiwenan">
								<text class="iconfont icon-AIwenan"></text>
								<text class="fs-15">优化提示词</text>
							</view>
							<view class="btn-tag py-9 px-12 flex  flex-center gap-4 round-6 " @click="setPrompt"
								v-if="promptList.length>0">
								<text class="iconfont icon-suiji "></text>
								<text class="fs-15">随机提示词</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="mt-20">
				<yTitle>
					<template #icon>
						<text class="iconfont icon-tupian fw-400"></text>
					</template>
					参考图片{{form.type==1?'(可选)':'(必填)'}}
				</yTitle>

				<view class="mt-12 bg-black-1 round-12  p-8 ">
					<view class="h-150 w-p-100 round-12 border-blue flex flex-center p-2"
						style="border-style: dashed !important;" @click="uploadImage">
						<view class="flex-1 h-p-100 flex-column gap-4 flex flex-center " v-if="!form.image_url">
							<text class="iconfont icon-tianjia fs-24 text-blue"></text>
							<text class="fs-14 text-blue">添加图片</text>
						</view>
						<view class="relative h-p-100" v-else style="width: fit-content;height: fit-content;">
							<view class="absolute top-6 right-6 w-16 h-16 flex flex-center round-circle"
								style="background: rgba(0,0,0,0.5);" @click="form.image_url=''">
								<text class="iconfont icon-guanbi fs-10"></text>
							</view>
							<image :src="form.image_url" class="h-p-100" mode="heightFix"></image>
						</view>
					</view>
					<view class="flex flex-x-space-between flex-y-center mt-12">
						<view class="fs-12 mt-12 text-999">*图片不可含人物，否则视频生成会失败</view>
						<view class="btn-tag py-9 px-12 flex flex-center gap-4 round-6 " @click="toM">
							<text class="iconfont icon-lishisucai fs-18"></text>
							<text class="fs-15">历史素材</text>
						</view>
					</view>
				</view>
			</view>

			<view class="mt-20">
				<yTitle>
					<template #icon>
						<text class="iconfont icon-moshi fw-400"></text>
					</template>
					生成模式
				</yTitle>
				<view class="mt-12">
					<y-tabs :list="videoTypeList" v-model="form.video_type" class="mt-12"></y-tabs>
				</view>
			</view>

			<view class="mt-20">
				<yTitle>
					<template #icon>
						<text class="iconfont icon-shipin fw-400"></text>
					</template>
					视频比例
				</yTitle>
				<view class="mt-12">
					<y-tabs :list="ratioList" v-model="form.aspectRatio" class="mt-12"></y-tabs>
				</view>
			</view>

			<view class="mt-20">
				<yTitle>
					<template #icon>
						<text class="iconfont icon-zonghaoshishichang fw-400"></text>
					</template>
					视频时长
				</yTitle>
				<view class="mt-12">
					<y-tabs :list="durationList" v-model="form.duration"></y-tabs>
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="mt-20 " v-if="WEBCONFIG?.wx_ad_status.includes('wx_banner')">
				<ad :unit-id="WEBCONFIG?.wx_banner" ad-theme="white">
				</ad>
			</view>
			<!-- #endif -->
		</view>
		<y-bottom>
			<view class="flex flex-y-center gap-20 px-16 pt-7">
				<view class="flex flex-column gap-4 flex-y-center" @click="$page.open('/pages/works/index')">
					<text class="iconfont icon-wodezuopin text-blue fs-24"></text>
					<text class="fs-12">我的作品</text>
				</view>
				<view class="flex-1 flex-column flex py-5 gap-3 gradient round-8 text-center"
					@click="usagePopup.open()">
					<text>立即生成</text>
					<text class="fs-12">{{getText}}</text>
				</view>
			</view>
		</y-bottom>



		<y-popup ref="adPopup" mode='bottom' backgroundColor="#fff" round='12' zIndex="100">
			<view class="py-18 px-30 ">
				<view class="text-center fs-20 fw-600 text-black">{{getAdText}}</view>
				<view class="flex relative flex-x-space-evenly my-18 ">
					<view class="flex-column flex flex-center gap-12">
						<view class="box-bg gradient flex flex-center fs-18"> 完成50%</view>
						<view class="w-13 h-13 round-circle " :class="getRatio>=50?'bg-blue-1':'bg-grey'"
							style="z-index: 99;"></view>
					</view>
					<view class="flex-column flex flex-center gap-12">
						<view class="box-bg gradient flex flex-center fs-18"> 获得一次</view>
						<view class="w-13 h-13 round-circle bg-grey" style="z-index: 99;"></view>
					</view>
					<view class="absolute bottom-3 left-0 right-0 round-30  h-7">
						<progress stroke-width="7" border-radius="30" :percent='getRatio' activeColor="#426EFC"
							backgroundColor="#EDEDED"></progress>
					</view>
				</view>

				<view class="flex-1 round-8 gradient text-green text-center py-15 fs-16 fw-600" @click="show()">
					观看视频
				</view>

				<view class=" round-8  text-black text-center py-15 fs-16 fw-600 mt-12"
					style="background-color: #EDEDED;" @click="adPopup.close();$page.open('/pages/level/index')">
					开通会员
				</view>
			</view>
			<view @click="adPopup.close()"
				class=" w-30 h-30 text-grey-1 round-circle flex flex-center absolute right-10 top-18"
				style="background: rgba(116,116,128,0.08);;">
				<text class="iconfont icon-guanbi text-333 fs-14 fw-600"></text>
			</view>
		</y-popup>

		<y-popup ref="tipsPopup" mode="center" round="12" backgroundColor="#fff">
			<view class="text-center p-15 flex flex-column gap-16 text-black vw-70">
				<view class="fs-17">温馨提示</view>
				<view class="text-333">再看{{number}}个视频，即可领取1次免费 创作机会</view>
				<view class="grid-columns-2 gap-12">
					<view class="round-8 text-999 py-10 bg-grey-1" @click="tipsPopup.close()">坚持退出</view>
					<view class="gradient py-10 round-8 text-white" @click="show()">立即领取</view>
				</view>
			</view>
		</y-popup>


		<y-popup ref="pointTipsPopup" mode="center" round="12" backgroundColor="#fff">
			<view class="text-center p-15 flex flex-column gap-16 text-black vw-70">
				<view class="fs-17">温馨提示</view>
				<view class="text-333">当前算力不足，是否前往算力 中心充值算力？</view>
				<view class="grid-columns-2 gap-12">
					<view class="round-8 text-999 py-10 bg-grey-1" @click="pointTipsPopup.close()">我再看看</view>
					<view class="gradient py-10 round-8 text-white" @click="$page.open('/pages/plans/index')">立即前往
					</view>
				</view>
			</view>
		</y-popup>

		<y-popup ref="successPopup" mode="center" round="12" backgroundColor="#fff">
			<view class="text-center  text-black vw-70 round-12">
				<view class="py-20 text-white gradient">
					<view>恭喜你，获得免费创作次数</view>
					<view class="flex flex-x-center flex-y-baseline mt-20">
						<text style="font-size: 36px;font-weight: 600;">1</text>
						<text>次</text>
					</view>
				</view>
				<view class="p-16">
					<view class='text-333 pb-20' style="padding-left: 44px;padding-right: 44px;">
						再看{{WEBCONFIG?.ad_number}}个视频，可领取1次免费 创作机会</view>
					<view class="grid-columns-2 gap-12">
						<view class="round-8 text-999 py-10 bg-grey-1" @click="successPopup.close()">坚持退出</view>
						<view class="gradient py-10 round-8 text-white" @click="show()">立即领取</view>
					</view>
				</view>
			</view>
		</y-popup>

		<yAiWenan ref="aiwaPopup" @success="onSuccess" :duration="form.duration" :prompt="form.prompt"></yAiWenan>
		<yUsage ref="usagePopup" @onSelected="onSelected" :type="form.type" :video_type="form.video_type"></yUsage>

		<view class="fixed right-0 flex flex-column gap-12" style="top:60%;z-index: 801;">
			<view class="item bg-black-1" @click="$page.open('/pages/works/case') " v-if="WEBCONFIG?.is_show_case==1">
				<view class=" round-circle p-4 boxxx flex flex-column gap-1">
					<image src="/static/image/case.png" class="w-30 h-30 round-circle" mode="aspectFill">
					</image>
					<text class="fs-14">案例</text>
				</view>
			</view>

			<view class="item bg-black-1" @click="$page.open('/pages/user/index') ">
				<view class=" round-circle p-4 boxxx flex flex-column gap-1">
					<image :src="USERINFO?.avatar" v-if="USERINFO?.id" class="w-30 h-30 round-circle" mode="aspectFill">
					</image>
					<text class="fs-14">我的</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { onMounted, reactive, ref, computed, watch } from 'vue';
	import { onShow, onLoad, onPageScroll } from '@dcloudio/uni-app'
	import ySetup from './modules/y-setup.vue'
	import yTitle from './modules/y-title.vue'
	import yAiWenan from './modules/y-ai-wenan.vue'
	import yUsage from './modules/y-usage.vue';
	import { $page, $http, $tool } from '@/utils'
	import { useRefs, useUserStore, useWebConfigStore } from '@/stores'
	import { useStorage } from '@/utils/storeage.js'
	import { useInterstitialAd } from '@/composables/useInterstitialAd.js';
	import { initRewardedVideoAd } from '@/composables/ad.js'
	const { init, show } = initRewardedVideoAd();
	const aiwaPopup = ref(null)
	const usagePopup = ref(null)
	const pointTipsPopup = ref(null)
	const safeBottom = ref(20)
	const number = ref(0)
	const initBottom = async () => {
		const system = await uni.getSystemInfoSync()
		const bottomInset = system.screenHeight - system.safeArea.bottom
		if (bottomInset > 0) {
			safeBottom.value = bottomInset
		}
	}
	const tipsPopup = ref(null)
	const successPopup = ref(null)
	const { USERINFO } = useRefs(useUserStore())
	const { WEBCONFIG } = useRefs(useWebConfigStore())
	const { hasLogin, setUserInfo, getUserInfo, setToken } = useUserStore()
	const ratioList = [
		{ label: '9:16（竖屏）', value: '9:16' },
		{ label: '16:9（横屏）', value: '16:9' },
	];
	const durationList = ref([
		{ label: '10秒', value: 10, isHot: false, tips: '' },
		{ label: '15秒', value: 15, isHot: true, tips: '' },
		{ label: '25秒', value: 25, isHot: false, tips: '*生成时间较久，失败概率高，需耐心等待~' },
	]);
	const videoTypeList = ref([
		{ label: '快速模式', value: 20 },
		{ label: '慢速模式', value: 10, tips: '*人多需排队等候~' },
		{ label: 'Pro模式', value: 30 },
	]);
	const getAdText = computed(() => {
		const a = USERINFO?.value?.ad_number ? USERINFO.value.ad_number : 0
		const b = WEBCONFIG?.value?.ad_number ? WEBCONFIG.value.ad_number : 0
		const number = b - a;
		if (number != 0) {
			return `再看${number}个视频即可获得`;
		}
		return '看视频领创作次数';
	})
	const getText = computed(() => {
		let data = {
			point: 0,
			productions: 0
		};
		if (form.value.video_type == 30) {
			data.point = WEBCONFIG.value?.pro_video_point;
			data.productions = WEBCONFIG.value?.pro_video_productions;
			return `消耗（${data.point}点算力或${data.productions}次创作次数）`;
		}
		if (form.value.type == 1) {
			if (form.value.video_type == 10) {
				data.point = WEBCONFIG.value?.routine_video_point || 0;
				data.productions = WEBCONFIG.value?.routine_video_productions || 0;
			}
			if (form.value.video_type == 20) {
				data.point = WEBCONFIG.value?.routine_video_point_fast || 0;
				data.productions = WEBCONFIG.value?.routine_video_productions_fast || 0;
			}
		} else if (form.value.type == 2) {
			data.point = WEBCONFIG.value?.ad_video_point || 0;
			data.productions = WEBCONFIG.value?.ad_video_productions || 0;
		}
		return `消耗（${data.point}点算力或${data.productions}次创作次数）`;
	})
	const onChangeTime = (e) => {
		form.value.duration = e.value
	}
	const adPopup = ref(null)
	const form = ref({
		type: 1,
		aspectRatio: '9:16',
		prompt: '',
		image_url: '',
		product_name: '',
		duration: 10,
		usage: 0,
		video_type: 20
	})
	const promptList = ref([])
	const onSuccess = (e) => {
		form.value.prompt = e
	}
	onLoad((e) => {
		getPrompt()
		if (e.data) {
			const data = JSON.parse(e.data);
			form.value.prompt = data.prompt
			form.value.image_url = data.image_url
			form.value.type = data.type
			form.value.product_name = data.product_name
			form.value.aspectRatio = data.aspectRatio
			form.value.duration = data.duration
		}
		uni.$once('initConfig', () => {

			if (WEBCONFIG.value.is_show_25 == 0) {
				durationList.value = [
					{ label: '10秒', value: 10, isHot: false, tips: '' },
					{ label: '15秒', value: 15, isHot: true, tips: '' },
				];
			}

			initVideoTypeList()

			// #ifdef MP-WEIXIN
			if (WEBCONFIG?.value?.wx_ad_status.includes('wx_interstitial')) {
				const { initAd } = useInterstitialAd(WEBCONFIG?.value.wx_interstitial_time)
				initAd(WEBCONFIG?.value.wx_interstitial);
			}
			if (WEBCONFIG?.value.wx_ad_status.includes('wx_rewarded')) {
				init(WEBCONFIG?.value.wx_rewarded, (e) => {
					if (e == 'reward') {
						usagePopup.value.close();
						adPopup.value.close();
						$http.post('User/addAdNumber').then(res => {
							getUserInfo();
							if (res.data.status) {
								tipsPopup.value.close()
								successPopup.value.open();
							} else {
								number.value = res.data.number
								successPopup.value.close();
								tipsPopup.value.open()
							}
						})
					} else {
						$tool.toast('未观看完成,无法获得奖励');
					}
				});
			}
			// #endif
		})

		uni.$on('meaterial', (e) => {
			form.value.image_url = e
		})

	})

	const getPrompt = () => {
		$http.get('Prompt/getList').then(res => {
			promptList.value = res.data
		})
	}

	const uploadImage = async () => {
		try {
			const tmpFiles = await uni.chooseImage({
				count: 1,
			})
			const result = await $http.upload('Upload/upload', {
				filePath: tmpFiles.tempFilePaths[0],
				name: 'file',
				is_hide: 1
			});
			form.value.image_url = result.data.url
			await $http.post('Material/add', { url: result.data.url });
			$tool.toast('上传成功');
		} catch (error) {
			console.log(error)
			$tool.toast('上传失败');
		}
	}

	const getRatio = computed(() => {
		const a = USERINFO?.value?.ad_number ? USERINFO.value.ad_number : 0
		const b = WEBCONFIG?.value?.ad_number ? WEBCONFIG.value.ad_number : 0
		if (b == 0 || a == 0) {
			return 0;
		}
		const number = USERINFO?.value.ad_number / WEBCONFIG?.value?.ad_number
		return Math.floor(number * 100)
	})
	const onSelected = async (e) => {
		if (e == 2) {
			return show();
		}
		if (e == 99) {
			usagePopup.value.close()
			pointTipsPopup.value.open();
			return;
		}
		form.value.usage = e;
		handGenVideo()
	}
	const handGenVideo = async () => {
		uni.showLoading({
			title: '任务创建中...',
			mask: true
		})
		await $http.post('Generate/generateSora', form.value);
		$tool.toast('任务创建成功');
		usagePopup.value.close()
		setTimeout(() => {
			$page.open('/pages/works/index');
		}, 300)
	}


	const toM = () => {
		$page.open('/pages/material/index');
	}

	const login = () => {
		let data = {
			pid: 0,
			code: '',
		};
		const pid = useStorage().get('PID')
		data.pid = pid || 0
		uni.showLoading({
			title: '登录中...'
		})
		uni.login({
			provider: 'weixin',
			success(res) {
				data.code = res.code
				$http.post('User/login', data).then(res => {
					$tool.toast('登录成功', 'success');
					setToken(res.data.token, res.data.ttl)
					getUserInfo()
				})
			}
		})
	}
	const openAiwenan = () => {
		if (form.value.prompt == '') {
			return $tool.toast('请输入描述词');
		}
		aiwaPopup.value.open();
	}
	const setPrompt = () => {
		if (promptList.value.length < 1) return;
		const index = getRandomInt(0, promptList.value.length)
		const prompt = promptList.value[index].prompt;
		form.value.prompt = prompt
	}
	const getRandomInt = (min, max) => {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}
	watch(() => form.value.duration, (v) => {
		if (v == 25) {
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 99999,
				})
			}, 50)
		}
	})
	watch(() => form.value.video_type, (e) => {
		const baseList = [
			{ label: '10秒', value: 10 },
			{ label: '15秒', value: 15 },
		];
		if (e === 30) {
			const commonTips = '*生成时间较久，需耐心等待~';
			durationList.value = [
				...baseList.map(i => ({ ...i, disable: true })),
				{ label: '25秒', value: 25, tips: commonTips, isHot: true },
			];
			form.value.duration = 25;
			return;
		}
		const commonTips = '*生成时间较久，失败概率高，需耐心等待~';
		const show25 = WEBCONFIG.value.is_show_25 != 0;
		durationList.value = [
			...baseList.map((i, idx) => ({
				...i,
				isHot: idx === 1,
				tips: '',
			})),
			...(show25 ? [{ label: '25秒', value: 25, isHot: false, tips: commonTips }] : [])
		];
		form.value.duration = 15;
	})

	const initVideoTypeList = () => {
		const { type } = form.value
		const config = WEBCONFIG.value
		if (type == 1) {
			if (config.is_user_select == 0) {
				const typeMap = {
					10: [
						{ label: '慢速模式', value: 10, tips: '*人多需排队等候~' },
						{ label: 'Pro模式', value: 30 },
					],
					20: [
						{ label: '快速模式', value: 20 },
						{ label: 'Pro模式', value: 30 },
					],
				}
				videoTypeList.value = typeMap[config.video_type] || []
				form.value.video_type = config.video_type
				return
			}

			videoTypeList.value = [
				{ label: '快速模式', value: 20 },
				{ label: '慢速模式', value: 10, tips: '*人多需排队等候~' },
				{ label: 'Pro模式', value: 30 },
			]
			form.value.video_type = 20
			return
		}

		videoTypeList.value = [
			{ label: '普通模式', value: 0 },
			{ label: 'Pro模式', value: 30 },
		]
		form.value.video_type = 0
	}


	onMounted(() => {
		initBottom()
	})
	onShow(() => {
		if (hasLogin()) {
			getUserInfo();
		} else {
			login()
		}
	})
</script>

<style>
	.avatar {
		width: 72rpx;
		height: 72rpx;
	}

	.pb-50 {
		padding-bottom: 50px;
	}

	.box-bg {
		width: 112px;
		height: 74px;
		border-radius: 24rpx;
		position: relative;
	}

	.box-bg::after {
		content: "";
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: -8px;
		width: 0;
		height: 0;
		border-left: 8px solid transparent;
		border-right: 8px solid transparent;
		border-top: 8px solid #426EFC;
	}

	.box-bg::before {
		content: "";
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: -9px;
		width: 0;
		height: 0;
		border-left: 9px solid transparent;
		border-right: 9px solid transparent;
		border-top: 9px solid #426EFC;
	}

	.ai {
		background: linear-gradient(90deg, #C433FE 0%, #F13697 100%);
	}

	.item {
		position: relative;
		border-radius: 50px 0 0 50px;
		padding: 6px 14px;
		z-index: 0;
	}

	.item::before {
		content: "";
		position: absolute;
		inset: 0;
		border-radius: 50px 0 0 50px;
		padding: 1px;
		background: linear-gradient(90deg, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0));
		-webkit-mask:
			linear-gradient(#fff 0 0) content-box,
			linear-gradient(#fff 0 0);
		-webkit-mask-composite: xor;
		mask-composite: exclude;
		z-index: -1;
	}
</style>